import {
  getPage,
  getImage
} from '../../utils/config';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import {
  promisify,
  http,
  $toast,
  $query
} from '../../utils/utils';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    getImage: getImage,
    loading: 0,
    logged: 0,
    userId: '',
    loaddone: false,
    abnor: false,
    imgheights: {},
    curBannerHeight: 0,
    showtips: 0,
    xqList: [],
    isCallMsg: false,
    key_height: 0,
    parent_id: 0,
    re_nickname: '',
    fileList: [],
    re_nickname: '',
    pl_value: null,
    plVal: null,
    input_place: '说点什么...',
    pl_list: [],
    plListPage: 1,
    plListPages: 0,
    openId: null
  },
  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  // 去详情页面
  goCompanydetail(e){
    let { id } = e.currentTarget.dataset||'';
    if(!id) return
    wxApi.navigateTo('/pages/companydetail/index', {
      id
    });
  },
  /**
   * 返回上一页
   */
  goBackTap() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },
  gohome() {
    wx.switchTab({
      url: getPage.home,
    })
  },
  updateDot(data) {
    let dots = data.detail.dots;
    this.setData({
      dots
    })
  },
  callphone() {
    let {
      logged,
      shopInfo,
      showtips,
      contacters
    } = this.data;
    let _this = this;
    var itemList = [];
    contacters.forEach(element => {
      itemList.push(element.contacter + " " + element.tel);
    });
    if (logged) {
      if (showtips == 0) {
        wx.showModal({
          title: '防骗提醒',
          content: '陌生电话要警惕，要求转账不要理',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              _this.setData({
                showtips: 1
              });
              wx.showActionSheet({
                itemList: itemList,
                success(res) {
                  console.log(res.tapIndex);
                  wx.makePhoneCall({
                    phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }
          }
        })
      } else {
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            console.log(res.tapIndex);
            wx.makePhoneCall({
              phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
              success: function () {
                console.log("拨打电话成功！")
              },
              fail: function () {
                console.log("拨打电话失败！")
              }
            })
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })

        console.log(this.data.contacters)
      }
    } else {
      this.jumpLogin();
    }
  },

  // 失去焦点
  keyboardBlur() {
    this.setData({
      isCallMsg: false,
      pl_value: '',
      fileList: []
    })
  },

  getKeyboardChangeHight(e) {
    let key_height = e?.detail?.height;
    console.log('key_height===2222222', key_height)
    this.setData({
      key_height,
    })
  },

  getKeyboardHight(e) {
    let key_height = e?.detail?.height;
    console.log('key_height===11111', key_height)
    this.setData({
      key_height,
    })
  },
  goCallMsg(e) {
    let p_id = e.currentTarget.dataset.id || 0
    let re_nickname = e.currentTarget.dataset.nickname || ''
    let {
      place
    } = e.currentTarget.dataset
    console.log('eeeeeeeeee', p_id, re_nickname, place)
    let input_place = '说点什么...'
    if (place) {
      input_place = '回复 @' + place
    }

    let {
      openId
    } = this.data;
    console.log('openId===',openId)
    // 评论需要获取openId
    if (openId) {
      this.setData({
        isCallMsg: true,
        parent_id: p_id,
        re_nickname,
        input_place
      })
    } else {
      wx.login({
        //获取code 使用wx.login得到的登陆凭证，用于换取openid
        success: (res1) => {
          console.log(res1)
          http.post(api.default, {
            data: {
              action: 'getweixininfo',
              code: res1.code
            }
          }).then((res) => {
            this.setData({
              isCallMsg: true,
              parent_id: p_id,
              re_nickname,
              input_place,
              openId: res.data.data.openid,
              session_key: res.data.data.session_key,
            })
          });
        }
      });
    }
  },
  keyboradInput(e) {
    console.log('eee', e)
    let pl_value = e.detail.value;
    this.setData({
      pl_value
    })
  },
  // 发送评论-确认是否有openId
  handleAddPinglun() {
    let {
      id,
      userId,
      parent_id,
      fileList,
      re_nickname,
      pl_value,
      openId
    } = this.data;
    console.log('openId===========', openId)
    if (!pl_value && fileList.length == 0) return $toast('请输入评论内容')
    let params = {
      action: 'addxuqiucommoents',
      openid: openId,
      userid: userId,
      xuqiu_id: id,
      content: pl_value,
      parent_id,
      fileList: fileList[0],
      re_nickname
    }
    http.post(api.default, {
      data: params
    }).then(() => {
      $toast(`评论成功`, {
        icon: 'success'
      });
      this.keyboardBlur()
      this.getXqPinglunPage(res => {
        this.setData({
          pl_list: res.list,
          pl_num: res.num
        })
      })
    })
  },
  

  gotousu() {
    let {
      logged,
      model,
      nickname
    } = this.data;
    if (logged) {
      wxApi.navigateTo(getPage.tousu + "?id=''" + "&name=" + nickname + "&type=发布" + "&title=" + model.title);
    } else {
      this.jumpLogin();
    }
  },

  /**
   * 喜欢
   */
  followLike() {
    var {
      logged,
      userId,
      id,
      likes_num
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'like_xuqiu',
          userid: userId,
          id: id,
        }
      }).then((res) => {
        let {
          errmsg,
          data
        } = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        this.setData({
          is_like: data,
          likes_num: data?likes_num+1:likes_num-1
        });
      })
    } else {
      this.jumpLogin();
    }
  },
  /**
   * 关注店铺
   */
  followClick() {
    var {
      logged,
      userId,
      id,
      is_fav,
      num
    } = this.data;
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'fav_xuqiu',
          userid: userId,
          id: id,
        }
      }).then((res) => {
        let {
          errmsg,
          data
        } = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        this.setData({
          is_fav: data,
          num: data?num+1:num-1
        });
      })
    } else {
      this.jumpLogin();
    }
  },

  /**
   * 跳转登录页
   */
  jumpLogin() {
    wxApi.setStartPage({
      id: this.data.shopid
    });
    wxApi.navigateTo(getPage.login);
  },


  /**
   * 监听页面--滚动
   */
  scrollChange(e) {

  },
  onPreviewImage(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    var showmenu = true;
    const {
      swiper
    } = this.data;
    console.log(data.id);
    const item = swiper[data.id];
    wx.previewImage({
      urls: swiper.map((item) => api.imageCdn + item.picurl),
      current: api.imageCdn + item.picurl,
      showmenu,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  gochat() {
    var {
      logged,
      model,
      headurl,
      nickname,
      swiper,
      headurl,
      model,
      id
    } = this.data;
    console.log(logged);
    if (logged) {
      let xuqiuObj = {
        id:id,
        picurl:swiper.length?swiper[0].picurl:'',
        headurl,
        nickname,
        title:model.title
      }
      console.log('xuqiuObj====',xuqiuObj)
      let xuqiuInfo = encodeURIComponent(JSON.stringify(xuqiuObj))
      wxApi.navigateTo(getPage.chat, {
        user_name: nickname,
        img: headurl,
        touserid: model.userid,
        xuqiuInfo
      });

    } else {
      this.jumpLogin();
    }

  },
  mediaload(e) {
    console.log('mediaload---------', e)
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },

  showDetailImg(e) {
    console.log(e)
    let cur_url = e.currentTarget.dataset.cur+ '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc=';
    let urls = this.data.xqList.map(m => {
      return m + '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc='
    })
    wx.previewImage({
      urls: urls,
      current: cur_url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    /**
     * 店铺id
     */
    console.log('optionsssssssssssss', options)
    if (JSON.stringify(options) !== '{}') {
      this.setData({
        id: options.id
      });
    }
    //获取路由数量
    this.setData({
      getPages: getCurrentPages().length
    })
    /**
     * 获取system信息
     */
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
      console.log(this.data.window);
    });

    /**
     * 获取用户信息 
     */
    let logged, userId, openId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
      openId = res.data.user.openid;
      console.log('oooooppppp',res.data.user,openId)
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId,
        openId
      });
      /**
       * 获取店铺信息
       */
      let {
        id,
        pageSize,
        loaddone,
        abnor
      } = this.data;

      //第一部分数据加载
      http.post(api.default, {
        data: {
          action: 'getxuqiuinfo',
          id: id,
          userid: userId||''
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log(data);
        let xqArr = data.xqlist && data?.xqlist.map(m => m.url)

        this.setData({
          model: data.model,
          shopid: data.shopid,
          swiper: data.pics,
          xqList: xqArr,
          nickname: data.nickname,
          headurl: data.headurl,
          loading: 1,
          is_fav: data.is_fav,
          is_like: data.is_like,
          likes_num: data.model.likes_num,
          num: data.model.num
        });
        console.log('-----------', this.data.imgheights);
      });

      this.getXqPinglunPage(res => {
        this.setData({
          pl_list: res.list,
          pl_num: res.num
        })
      })


    });

    /**
     * scrollTop
     */
    this.scrollTop = 0;
    this.scrollHeight = 0;

    /**
     * 获取收缩对象高度
     */
    $query.select('#headInfo', (data) => {
      this.headInfo = data;
    });
  },

  // 删除
  handleDelpinglun(e) {
    let pl_id = e.currentTarget.dataset.id;
    let that = this;
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '是否删除此评论？',
      success(res) {
        if (res.confirm) {
          http.post(api.default, {
            data: {
              action: 'del_xuqiucomments',
              userid: that.data.userId,
              id: pl_id,
            }
          }).then(res => {
            $toast(`删除成功`, {
              icon: 'success'
            });
            that.getXqPinglunPage(res => {
              that.setData({
                pl_list: res.list,
                pl_num: res.num
              })
            })
          })
        }
      },
    })
  },

  // 展开更多回复
  showAllList(e) {
    let plId = e.currentTarget.dataset.id;
    let {
      pl_list
    } = this.data;
    pl_list.forEach(item => {
      if (item.id == plId) {
        item.isdefalut = true
      }
    })
    this.setData({
      pl_list
    })
  },

  /**
   * 获取产品数据
   */
  getXqPinglunPage(cb, a = false) {
    let {
      plListPage,
      plListPages,
      id,
    } = this.data;
    http.post(api.default, {
      data: {
        action: 'getxuqiucomments',
        pageindex: plListPage,
        xuqiu_id: id,
      }
    }, a).then((res) => {
      const {
        data
      } = res.data;
      //是否加载完毕
      this.setData({
        plListPages: data.pages
      });
      let pl_list = data.list;
      pl_list.forEach(item => {
        item.addtime = item.addtime.slice(0, 10)
        item.isdefalut = false
        if (item.list.length > 0) {
          item.list.forEach(c_item => {
            c_item.addtime = c_item.addtime.slice(0, 10)
          })
          item.defList = item.list.slice(0, 1)
        }
      })
      cb && cb({
        list: pl_list,
        num: data.data
      });
    });
  },

  // 预览图片
  showCallImg(e) {
    let url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  // 预览图片
  showImg() {
    let {
      fileList
    } = this.data;
    wx.previewImage({
      urls: fileList,
      current: fileList[0],
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  // 删除图片
  deleteImg() {
    this.setData({
      fileList: []
    })
  },
  clickImg() {
    let {
      pl_value
    } = this.data;
    if (pl_value) {
      this.setData({
        plVal: pl_value
      })
    }
  },
  // 发送图片
  afterRead(event) {
    const {
      file
    } = event.detail;
    var that = this;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    for (var i = 0; i < file.length; i++) {
      var item = file[i];
      uploadImage({
        filePath: item.url,
        dir: "users",
        success(res) {
          // 上传完成发送
          var img_url = api.imageCdn + res
          console.log('api.imageCdn + res', api.imageCdn + res)
          that.setData({
            fileList: [img_url],
            isCallMsg: true
          })
          if (that.data.plVal) {
            that.setData({
              pl_value: that.data.plVal
            })
          }
        },
        fail(res) {
          $toast(`图片上传失败${JSON.stringify(res)}`);
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    console.log('到底了')
    let {
      plListPage,
      plListPages
    } = this.data;
    //未请求完且未在加载中
    if (plListPages > plListPage) {
      plListPage++;

      //显示加载效果
      this.setData({
        plListPage
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.getXqPinglunPage(res => {
        let {
          pl_list
        } = this.data;
        console.log('底部---------getProductsInfo')
        this.setData({
          pl_list: pl_list.concat(res.list),
          pl_num: res.num
        })
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var pageshare = getPage.xuqiudetail + "?id=" + this.data.id;
    var picurl = "";
    if (this.data.swiper.length > 0)
      picurl = api.imageCdn + this.data.swiper[0].picurl;
    return {
      title: `【可居-业主需求】${this.data.model.title}`,
      imageUrl: picurl,
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})